package com.monkeyk.sos.web.controller.sys.applicationmgt;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.monkeyk.sos.domain.model.ApplicationDetails;
import com.monkeyk.sos.domain.model.CooperDetails;
import com.monkeyk.sos.service.SysApplicationService;
import com.monkeyk.sos.util.DateFormatTool;
import com.monkeyk.sos.util.DateJsonValueProcessor;
import com.monkeyk.sos.util.PageData;
import com.monkeyk.sos.util.Pager;

/**
 * 
 * 
 ***************************************************************  
 * <b>项目名称：</b>腾邦开放平台<br>
 * <b>程序名称：</b>应用服务控制层<br>
 * <b>日期：</b>2015年12月9日 上午11:10:26<br>
 * <b>作者：</b>Haiquan Yin<br>
 * <b>模块： </b>管理后台<br>
 * <b>描述： </b>应用服务管理<br>
 * <b>备注： </b><br>
 * ------------------------------------------------------------ 
 * 修改历史 
 * ------------------------------------------------------------ 
 * 序号               日期                       修改人                   修改原因 
 * ------------------------------------------------------------  
 *  
 * 修改备注： 
 * <p>@version</p>
 * <p></p>
 ***************************************************************
 */
@Controller
@RequestMapping("/sys/app")
public class AppManagementController {
	
     private static final Logger Log = Logger.getLogger(AppManagementController.class);
	
     @Resource
     private SysApplicationService sysApplicationService;
     
     /**
     * 
     * TODO 应用管理页面(application_Mgt.jsp)跳转方法
     * @date 2015年12月9日 上午11:17:30 
     * @author HaiQuan Yin
     *
     * @return
     */
    @RequestMapping("/skipapp")
    public String skipApplicationManagement() {
	    Log.info(DateFormatTool.getDate()+" 执行方法(/sys/app/skipapp.do)跳转应用管理页面(application_Mgt.jsp)");
	    return "/sys/applicationmgt/application_Mgt";
    }
    
    /**
     * 
     * TODO 根据应用ID获取合作方信息
     * @date 2015年12月18日 下午4:37:12 
     * @author HaiQuan Yin
     *
     * @param appId 应用ID
     * @param request
     * @param response
     */
    @RequestMapping(value="findcooperinfo",method=RequestMethod.POST)
    public void findCooperInfoByAppId(@RequestParam("appId") int appId,
    		HttpServletRequest request,HttpServletResponse response){
    	    response.setContentType("text/html;charset=UTF-8");
			try {
				PrintWriter out = response.getWriter();
				int coopId = sysApplicationService.findCoopIDByAppId(appId);
				CooperDetails cDetails = sysApplicationService.findCooperDetailById(coopId);
				JsonConfig config = new JsonConfig(); 
	   			config.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
	   			JSONObject jsonObject = JSONObject.fromObject(cDetails,config);
	   			if(Log.isInfoEnabled()){
	   				Log.info(DateFormatTool.getDate()+" 调用方法(findcooperinfo.do)根据应用ID获取合作方信息输入参数:[appId:"+appId+"]");
	   				Log.info(DateFormatTool.getDate()+" 调用方法(findcooperinfo.do)根据应用ID获取合作方信息输出总数:["+cDetails+"]");
	   			}
	   			out.print(jsonObject.toString());
				
			} catch (IOException e) {
				if (Log.isInfoEnabled()) {
	   				Log.info(DateFormatTool.getDate()+" 调用方法(findcooperinfo.do)根据应用ID获取合作方信息抛出异常信息:["+e.getMessage()+"]");
	   			}
			}
    }
    
    /**
     * 
     * TODO 分页查询应用信息
     * @date 2015年12月9日 下午3:35:19 
     * @author HaiQuan Yin
     * @param appName 应用名称
     * @param status 审核状态 
     * @param page 页数
     * @param rows 页面大小
     * @param sort 排序
     * @param order 
     * @param request
     * @param response
     */
    @RequestMapping(value="findapps",method=RequestMethod.POST)
   	public void findApps(@RequestParam("appName") String appName,@RequestParam("status") int status,
   			@RequestParam("page") int page,@RequestParam("rows") int rows,
   			@RequestParam("sort") String sort,@RequestParam("order") String order,
   			HttpServletRequest request,HttpServletResponse response){
   		try {
   			response.setContentType("text/html;charset=UTF-8");
   			PrintWriter out = response.getWriter();
   			Map<String, Object> paramMap = new HashMap<String, Object>();
   			paramMap.put("appName", (null!=appName&&!"".equals(appName))?URLDecoder.decode(URLDecoder.decode(appName,"utf-8"),"utf-8"):"");
   			paramMap.put("status", status);
   			Pager pager = new Pager(page, rows);
   			pager.setSort(sort);
   			pager.setOrder(order);
   			pager = sysApplicationService.findApps(paramMap, pager);
   			PageData<ApplicationDetails> pageData = new PageData<ApplicationDetails>();
   			List<ApplicationDetails> list = (List<ApplicationDetails>) pager.getData();
   			pageData.setRows(list);
   			pageData.setTotal(pager.getTotalResults());
   			JsonConfig config = new JsonConfig(); 
   			config.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
   			JSONObject jsonObject = JSONObject.fromObject(pageData,config);
   			if(Log.isInfoEnabled()){
   				Log.info(DateFormatTool.getDate()+" 调用方法(findapps.do)分页获取应用信息列表输入参数:[paramMap:"+paramMap+"]");
   				Log.info(DateFormatTool.getDate()+" 调用方法(findapps.do)分页获取应用信息列表输出总数:["+pager.getTotalResults()+"]");
   			}
   			out.print(jsonObject.toString());
   		} catch (Exception e) {
   			if (Log.isInfoEnabled()) {
   				Log.info(DateFormatTool.getDate()+" 调用方法(findapps.do)分页获取应用信息列表抛出异常信息:["+e.getMessage()+"]");
   			}
   		}
   	}
      
	/**
	 * 修改应用状态值
	 * 
	 * @param status        状态值
	 * @param ids           应用ID集
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="updateappstatus",method=RequestMethod.POST)
	public void updateAppStatus(@RequestParam("st") int status,@RequestParam("ids") String ids ,
			HttpServletRequest request,HttpServletResponse response){
		PrintWriter out = null;
		try {
			out = response.getWriter();
			List<Integer> idlList = new ArrayList<Integer>();
			if (null!=ids&&!"".equals(ids)) {
				String [] idlist = ids.split(",");
				if (null!=idlist&&idlist.length>0) {
					for (String id : idlist) {
						idlList.add(Integer.parseInt(id));
					}
					sysApplicationService.updateAppType(idlList, status);
				}
			}
			if(Log.isInfoEnabled()){
				Log.info(DateFormatTool.getDate()+" 调用方法(updateappstatus.do)修改应用状态值输入参数:[应用ID集(ids):"+ids+",有效状态(status):"+status+"]");
			}
			out.print(1);
		} catch (Exception e) {
			try {
				out = response.getWriter();
				out.print(0);
			} catch (IOException e1) {
			}
			if (Log.isInfoEnabled()) {
				Log.info(DateFormatTool.getDate()+" 调用方法(updateappstatus.do)修改应用状态值抛出异常信息:["+e.getMessage()+"]");
			}
		}
	}
}